import os
import pickle
import random,hashlib

from user import User

class Manager:
    def __init__(self):
        '管家类'
        self.path = os.path.dirname(os.path.abspath(__file__))
        self.filesPath=os.path.join(os.path.dirname(self.path),'userFiles')
        if not os.path.isdir(self.filesPath):
            os.mkdir(self.filesPath)
        self.users = self.loadUsers()

    def loadUsers(self):
        '加载数据'
        usersPath = os.path.join(self.path, 'users.dat')
        if os.path.isfile(usersPath):
            with open(usersPath, 'rb') as f:
                return pickle.load(f)
        else:
            return {}

    def loadInviteCodes(self):
        '加载邀请码'
        def createCodes(codesPath):
            '创建随机邀请码'
            import string
            words = string.ascii_letters+string.digits
            codes = [''.join(random.sample(words, 6)) for i in range(100)]
            codes = set(codes)
            print(codes)
            s = '\n'.join(codes)
            with open(codesPath, 'w', encoding='utf-8') as f:
                f.write(s)
            return codes
        codesPath = os.path.join(self.path, 'inviteCodes.txt')
        if os.path.isfile(codesPath):
            with open(codesPath, 'r', encoding='utf-8') as f:
                codes = f.readlines()
                codes = set(codes)
                inviteCodes = []
                for code in codes:
                    if code:
                        inviteCodes.append(code.strip())
                if inviteCodes == []:
                    self.inviteCodes = createCodes(codesPath)
                else:
                    self.inviteCodes = inviteCodes

        else:
            self.inviteCodes = createCodes(codesPath)

    def addUser(self, name, passwd, email, invitecode):
        '增加用户'
        ids = list(self.users.keys())
        try:
            userId = ids[-1]+1
        except IndexError:
            userId = 1
        user = User()
        user.ID = userId
        user.name = name
        user.passwd = passwd
        user.invitecode = invitecode
        self.users[userId] = user
        usersPath = os.path.join(self.path, 'users.dat')
        with open(usersPath, 'wb') as f:
            pickle.dump(self.users, f)
        userPath=os.path.join(self.filesPath, str(userId))
        if os.path.isdir(userPath):
            os.remove(userPath)
        else:
            os.mkdir(userPath)
    def checkNameAndPasswd(self,name,passwd):
        '检查用户名和密码'
        names=['']
        status=0
        for ID in self.users:
            user=self.users[ID]
            names.append(user.name)
            if user.name==name and user.passwd==passwd:
                status=ID
        return status

    def getRelaPath(self,path,ID):
        '获取相对目录'
        workpath=os.path.join(self.filesPath,str(ID))
        nowDir=os.path.dirname(path)
        nowDir=nowDir.split(workpath)[1]            
        if nowDir:
            nowDir=nowDir.split('/')
            nowDir=[str(i) for i in nowDir]
        else:
            nowDir='哎呀好奇怪'
        return nowDir
    
    def getFilesInfoById(self,userId):
        '根据用户id获取文件'
        files=[]
        userPath=os.path.join(self.filesPath,str(userId))
        for filepath,dirnames,filenames in os.walk(userPath):
            for filename in filenames:
                path=os.path.join(filepath,filename)
                with open(path, 'rb') as fp:
                    data = fp.read()
                    md5=hashlib.md5(data).hexdigest()
                cTime=os.path.getctime(path)
                mTime=os.path.getmtime(path)
                files.append({
                    'name':filename,
                    'path':os.path.join(filepath,filename),
                    'relaPath':self.getRelaPath(os.path.join(filepath,filename),userId),
                    'md5':md5 ,
                    'cTime':cTime,
                    'mTime':mTime,                 
                })
        return files
